package pkg

import (
	"errors"
	beego "github.com/beego/beego/v2/server/web"
	"github.com/dgrijalva/jwt-go"
	"strconv"
)

// @secretKey: JWT 加解密密钥
// @iat: 时间戳
// @seconds: 过期时间，单位秒
// @payload: 数据载体
// 生成token
func SetJwtToken(iat int64, payload string) (string, error) {
	secretKey, _ := beego.AppConfig.String("JwtSecretKey")
	jwtSeconds, _ := beego.AppConfig.String("JwtSeconds")
	atoi, _ := strconv.Atoi(jwtSeconds)
	seconds := int64(atoi)
	claims := make(jwt.MapClaims)
	claims["exp"] = iat + seconds
	claims["iat"] = iat
	claims["payload"] = payload
	token := jwt.New(jwt.SigningMethodHS256)
	token.Claims = claims
	return token.SignedString([]byte(secretKey))
}

// 解析token
func GetJwtTokenPayload(tokenString string) (string, float64, error) {
	secretKey, _ := beego.AppConfig.String("JwtSecretKey")
	token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
		return []byte(secretKey), nil
	})
	if err != nil {
		return "", 0, errors.New("token解析失败")
	}
	if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
		return claims["payload"].(string), claims["exp"].(float64), err
	}
	return "", 0, errors.New("token解析失败")
}
